package cn.jiahua.hospital.controller;

import cn.jiahua.hospital.config.AliPayConfig;
import cn.jiahua.hospital.constants.ResultEnum;

import cn.jiahua.hospital.dto.DoctorScheduleDto;
import cn.jiahua.hospital.dto.RefuntDto;

import cn.jiahua.hospital.dto.Result;
import cn.jiahua.hospital.pojo.Schedule;
import cn.jiahua.hospital.pojo.YOrder;
import cn.jiahua.hospital.service.AlipayService;
import cn.jiahua.hospital.service.ScheduleService;
import cn.jiahua.hospital.service.YOrderService;
import cn.jiahua.hospital.utils.ResultUtils;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
@RequestMapping("alipay")
public class AlipayController {

    @Autowired
    AliPayConfig aliPayConfig;

    @Resource
    YOrderService yOrderService;

    @Resource
    AlipayService alipayService;

    @Autowired
    ScheduleService scheduleService;


    //异步回调地址
    @GetMapping("notify")
    public void notify_url(HttpServletRequest request,HttpServletResponse response) {
        System.out.println("=====================notify_url=====================");
        //获取支付宝POST过来反馈信息
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            try {
                valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
            params.put(name, valueStr);
        }

        boolean signVerified = false; //调用SDK验证签名
        try {
            signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfig.getAlipayPublicKey(), aliPayConfig.getCharset(), aliPayConfig.getSignType());
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }

        //——请在这里编写您的程序（以下代码仅作参考）——

	/* 实际验证过程建议商户务必添加以下校验：
	1、需要验证该通知数据中的out_trade_no是否为商户系统中创建的订单号，
	2、判断total_amount是否确实为该订单的实际金额（即商户订单创建时的金额），
	3、校验通知中的seller_id（或者seller_email) 是否为out_trade_no这笔单据的对应的操作方（有的时候，一个商户可能有多个seller_id/seller_email）
	4、验证app_id是否为该商户本身。
	*/
        if(signVerified) {//验证成功
            //商户订单号
            try {
                String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            //支付宝交易号
            try {
                String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            //交易状态
            String trade_status = null;
            try {
                trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }

            if(trade_status.equals("TRADE_FINISHED")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //退款日期超过可退款期限后（如三个月可退款），支付宝系统发送该交易状态通知
            }else if (trade_status.equals("TRADE_SUCCESS")){
                //判断该笔订单是否在商户网站中已经做过处理
                //如果没有做过处理，根据订单号（out_trade_no）在商户网站的订单系统中查到该笔订单的详细，并执行商户的业务程序
                //如果有做过处理，不执行商户的业务程序

                //注意：
                //付款完成后，支付宝系统发送该交易状态通知
            }
            System.out.println("success");

        }else {//验证失败
            System.out.println("fail");

            //调试用，写文本函数记录程序运行情况是否正常
            //String sWord = AlipaySignature.getSignCheckContentV1(params);
            //AlipayConfig.logResult(sWord);
        }
    }

    //同步回调接口
    @GetMapping("return")
    public void return_url(HttpServletRequest request,HttpServletResponse response){
        System.out.println("===================return_url===================");
        //获取支付宝GET过来反馈信息
        try {
        Map<String,String> params = new HashMap<String,String>();
        Map<String,String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean signVerified = AlipaySignature.rsaCheckV1(params, aliPayConfig.getAlipayPublicKey(), aliPayConfig.getCharset(), aliPayConfig.getSignType()); //调用SDK验证签名

        //——请在这里编写您的程序（以下代码仅作参考）——
        if(signVerified) {
            //商户订单号
            String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //支付宝交易号
            String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");

            //付款金额
            String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");

            System.out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);

            //查询订单，添加支付宝交易号，修改订单状态
            HttpSession session = request.getSession();
            Integer isMorning = (Integer) session.getAttribute("isMorning");
            String time = (String) session.getAttribute("time");
            SimpleDateFormat std = new SimpleDateFormat("yyyy-MM-dd");
            Date date= std.parse(time);
            Integer doctorId = (Integer) session.getAttribute("doctorId");

            YOrder yOrder =  yOrderService.getYOrderById_orderid(out_trade_no);
            if(yOrder!=null){
                yOrder.setPatientsTime(date);
                yOrder.setAliTradeNo(trade_no);
                yOrder.setStatus(2);
                int i =  yOrderService.qdtxModifyYOrder(yOrder);
            }

            SimpleDateFormat sdf = new SimpleDateFormat("EEEE");
            String week = sdf.format(date);
            System.out.println(week);
            HashMap map = new HashMap();
            map.put("doctorId",doctorId);
            ArrayList<Schedule> list = (ArrayList) scheduleService.getScheduleListByMap(map);
            Schedule schedule  =list.get(0);
            schedule.setDoctorId(doctorId);
            if(isMorning==1){
                switch (week){
                    case "星期一":
                        schedule.setAmOne(schedule.getAmOne()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期二":
                        schedule.setAmTwo(schedule.getAmTwo()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期三":
                        schedule.setAmThree(schedule.getAmThree()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期四":
                        schedule.setAmFour(schedule.getAmFour()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期五":
                        schedule.setAmFive(schedule.getAmFive()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期六":
                        schedule.setAmSix(schedule.getAmSix()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期日":
                        schedule.setAmSeven(schedule.getAmSeven()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                }
            }else if(isMorning==2){
                switch (week){
                    case "星期一":
                        schedule.setPmOne(schedule.getPmOne()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期二":
                        schedule.setPmTwo(schedule.getPmTwo()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期三":
                        schedule.setPmThree(schedule.getPmThree()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期四":
                        schedule.setPmFour(schedule.getPmFour()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期五":
                        schedule.setPmFive(schedule.getPmFive()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期六":
                        schedule.setPmSix(schedule.getPmSix()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                    case "星期日":
                        schedule.setPmSeven(schedule.getPmSeven()-1);
                        scheduleService.updateSchedule_doctorId(schedule);
                        break;
                }
            }


        }else {
            System.out.println("验签失败");
        }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }catch (AlipayApiException ex){
            ex.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("===================支付成功======================");
        try {
            response.sendRedirect("/hospital/page/home.html");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //付款接口
    @ApiImplicitParams({
            @ApiImplicitParam(name = "WIDout_trade_no",value = "商户订单号"),
            @ApiImplicitParam(name = "WIDsubject",value = "订单名称"),
            @ApiImplicitParam(name = "WIDtotal_amount",value = "付款金额"),
            @ApiImplicitParam(name = "WIDbody",value = "商品描述"),
            @ApiImplicitParam(name = "doctorId",value = "医生ID"),
            @ApiImplicitParam(name = "isMorning",value = "上午还是下午"),
            @ApiImplicitParam(name = "time",value = "预约时间"),
    })
    @GetMapping("pay")
    public void pay(@RequestParam(value="WIDout_trade_no",required = false)String WIDout_trade_no,
                    @RequestParam(value="WIDsubject",required = false)String WIDsubject,
                    @RequestParam(value="WIDtotal_amount",required = false)String WIDtotal_amount,
                    @RequestParam(value="WIDbody",required = false)String WIDbody,
                    @RequestParam(value="doctorId",required = false)Integer doctorId,
                    @RequestParam(value="isMorning",required = false)Integer  isMorning,
                    @RequestParam(value="time",required = false) String time,
                    HttpServletResponse response,
                    HttpServletRequest request)  {
        System.out.println("==================hello=========================");
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getUrl(), aliPayConfig.getAppid(), aliPayConfig.getRsaPrivateKey(), "json", aliPayConfig.getCharset(), aliPayConfig.getAlipayPublicKey(), aliPayConfig.getSignType());
            //设置请求参数
            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            alipayRequest.setReturnUrl(aliPayConfig.getReturnUrl());
            alipayRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());
            HttpSession session = request.getSession();
            session.setAttribute("isMorning",isMorning);
            session.setAttribute("time",time);
            session.setAttribute("doctorId",doctorId);
            //商户订单号，商户网站订单系统中唯一订单号，必填
            String out_trade_no = new String(WIDout_trade_no.getBytes("ISO-8859-1"), "UTF-8");
            //付款金额，必填
            String total_amount = new String(WIDtotal_amount.getBytes("ISO-8859-1"), "UTF-8");
            //订单名称，必填
            String subject = new String(WIDsubject.getBytes("ISO-8859-1"), "UTF-8");
            //商品描述，可空
            String body = new String(WIDbody.getBytes("ISO-8859-1"), "UTF-8");
            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");

            //若想给BizContent增加其他可选请求参数，以增加自定义超时时间参数timeout_express来举例说明
            //alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\","
            //		+ "\"total_amount\":\""+ total_amount +"\","
            //		+ "\"subject\":\""+ subject +"\","
            //		+ "\"body\":\""+ body +"\","
            //		+ "\"timeout_express\":\"10m\","
            //		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
            //请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节

            //请求
            String result = alipayClient.pageExecute(alipayRequest).getBody();
//            String form = "";
//            form = client.pageExecute(alipay_request).getBody();
            response.setContentType("text/html;charset=" + aliPayConfig.getCharset());
            response.getWriter().write(result);//直接将完整的表单html输出到页面
            response.getWriter().flush();
            response.getWriter().close();
            //输出
            System.out.println(result);
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

//    @RequestParam(value="WIDout_trade_no",required = false)String WIDTRout_trade_no,
//    @RequestParam(value="WIDTRtrade_no",required = false)String WIDTRtrade_no,
//    @RequestParam(value="WIDTRout_request_no",required = false)String WIDTRout_request_no,
//    @RequestParam(value="WIDTRrefund_amount",required = false)String WIDTRrefund_amount,
//    @RequestParam(value="WIDTRrefund_reason",required = false)String WIDTRrefund_reason
//    @ApiImplicitParams({
//            @ApiImplicitParam(name = "WIDout_trade_no",value = "商户订单号",required = true),
//            @ApiImplicitParam(name = "WIDTRout_request_no",value = "退款号",required = true),
//            @ApiImplicitParam(name = "WIDTRrefund_amount",value = "退款金额",required = true),
//            @ApiImplicitParam(name = "WIDTRrefund_reason",value = "退款原因",required = false)
//    })

    @ApiOperation(value="退款",notes = "根据订单单号、退款金额等信息进行退款")
    @ApiImplicitParam(name = "refuntDto",value = "退款详情信息",required = true)
    @PostMapping("refund")
    public Result refund(@RequestBody Map<String,String> map, HttpServletResponse response)  {
        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(aliPayConfig.getUrl(), aliPayConfig.getAppid(), aliPayConfig.getRsaPrivateKey(), "json", aliPayConfig.getCharset(), aliPayConfig.getAlipayPublicKey(), aliPayConfig.getSignType());
            //设置请求参数
            AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();

            //商户订单号，商户网站订单系统中唯一订单号
            String out_trade_no = new String(map.get("WIDTRout_trade_no").getBytes("ISO-8859-1"), "UTF-8");
            //支付宝交易号
            //String trade_no = new String(refuntDto.getWIDTRtrade_no().getBytes("ISO-8859-1"), "UTF-8");
            //请二选一设置
            //需要退款的金额，该金额不能大于订单金额，必填
            String refund_amount = new String(map.get("WIDTRrefund_amount").getBytes("ISO-8859-1"), "UTF-8");
            //退款的原因说明
            String refund_reason = new String(map.get("WIDTRrefund_reason").getBytes("ISO-8859-1"), "UTF-8");
            //标识一次退款请求，同一笔交易多次退款需要保证唯一，如需部分退款，则此参数必传
            String out_request_no = new String(map.get("WIDTRout_request_no").getBytes("ISO-8859-1"), "UTF-8");

            alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"trade_no\":\"" + "" + "\","
                    + "\"refund_amount\":\"" + refund_amount + "\","
                    + "\"refund_reason\":\"" + refund_reason + "\","
                    + "\"out_request_no\":\"" + out_request_no + "\"}");

            //请求
            String result = alipayClient.execute(alipayRequest).getBody();
            JSONObject jsonObject = JSONObject.parseObject(result);
            JSONObject jsonObject02 = (JSONObject) jsonObject.get("alipay_trade_refund_response");
            //输出
            System.out.println(jsonObject02.get("code"));
            String code = (String) jsonObject02.get("code");
            if (code!=null && code.equals("10000")){
                System.out.println("***********退款成功***********");
                String orderId = map.get("WIDTRout_trade_no");
                if (orderId == null || orderId == "") {
                    return ResultUtils.returnFail(ResultEnum.FAIL_PARAM.getCode(), ResultEnum.FAIL_PARAM.getMsg());
                }
                //根据订单编号获取订单信息
                Map<String, Object> map02 = new HashMap<>();
                map02.put("orderid", orderId);
                List<YOrder> yOrderListByMapOfUser = yOrderService.getYOrderListByMapOfUser(map02);
                if (yOrderListByMapOfUser == null || yOrderListByMapOfUser.size() <= 0) {
                    return ResultUtils.returnFail(ResultEnum.FAIL_HAVE_NOT_EXIST.getCode(), ResultEnum.FAIL_HAVE_NOT_EXIST.getMsg());
                }

                //修改点订单的状态
                YOrder yOrder = yOrderListByMapOfUser.get(0);
                yOrder.setStatus(4);

                Integer integer = yOrderService.qdtxModifyYOrder(yOrder);

                if (integer <= 0) {
                    return ResultUtils.returnFail(ResultEnum.FAIL_USER_UPDATE.getCode(), ResultEnum.FAIL_USER_UPDATE.getMsg());
                }
                return ResultUtils.returnSuccess();
            }else{
                System.out.println("***********退款失败***********");
                return ResultUtils.returnFail("退款失败");
            }
//            response.setContentType("text/html;charset=" + aliPayConfig.getCharset());
//            response.getWriter().write(result);//直接将完整的表单html输出到页面
//            response.getWriter().flush();
//            response.getWriter().close();
        }catch (UnsupportedEncodingException e){
            e.printStackTrace();
        } catch (AlipayApiException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
            return ResultUtils.returnFail("退款失败");
        }
        return ResultUtils.returnFail();
    }


    @ApiOperation(value="退款",notes = "根据订单单号、退款金额等信息进行退款")
    @ApiImplicitParam(name = "refuntDto",value = "退款详情信息",required = true)
    @PostMapping("alipayRefund")
    public void alipayRefund(@RequestBody Map<String,String> map, HttpServletResponse response){
        boolean fall = false;
        String orderId = map.get("WIDTRout_trade_no");
        if (orderId == null || orderId == "") {
            try {
                response.sendRedirect("/hospital/page/error.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            boolean b = alipayService.alipayRefunt(map, response);
            if (b){
                response.sendRedirect("/hospital/page/user_info.html");
            }else{
                response.sendRedirect("/hospital/page/error.html");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
